package top.kiterunner.learning.concurrency_test.ReentrantLockDemo;


// 使用ReentrantLock可以进行尝试锁定tryLock，这样无法锁定，或者在指定时间内无法锁定，线程可以决定是否继续等待

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/7.
 */
public class ReentrantLockDemo3 {

    Lock lock = new ReentrantLock();

    public void method1() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " Running...");
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        boolean flag = false;
        try {
            lock.lockInterruptibly();
            flag = true;
            System.out.println(Thread.currentThread().getName() + " Running...");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (flag)
                lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo3 rcd3 = new ReentrantLockDemo3();

        Thread thread1 = new Thread(rcd3::method1, "Thread_1");

        thread1.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread thread2 = new Thread(rcd3::method2, "Thread_2");

        thread2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread2.interrupt();
    }
}
